package com.zcg.blogger.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zcg.blogger.exception.UserException;
import com.zcg.blogger.model.Propose;
import com.zcg.blogger.service.ProposeService;

@Controller
@RequestMapping("/propose")
public class ProposeController {
	
	@Resource
	private ProposeService proposeService;
	
	/**
	 * 增加建议页面
	 * @param propose
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(@ModelAttribute Propose propose,Model model){
		return "propose/add";
	}
	
	/**
	 * 增加建议
	 * @param propose
	 * @param br
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/add","/list","/"},method=RequestMethod.POST)
	public String add(@Validated Propose propose, BindingResult br, Model model){
		if(propose.getUser().getId() == 0){
			throw new UserException("请先登录");
		}
		if (br.hasErrors()) {
			return "propose/add";
		}
		proposeService.add(propose);
		model.addAttribute(propose);
		return "redirect:./";
	}
	
	/**
	 * 建议列表
	 * @param propose
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value={"/list","/"},method=RequestMethod.GET)
	private String list(@ModelAttribute Propose propose,Model model, HttpSession session) {
		List<Propose> proposes = proposeService.loadProposeAll();
		int proposeCount = proposeService.countAll();
		model.addAttribute("proposes", proposes);
		model.addAttribute("proposeCount",proposeCount);
		model.addAttribute("url", "propose/");
		return "propose/index";
	}
}
